package com.wertop.viid.common.utils;


import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.wertop.viid.entity.DigestAuthInfo;

/**
 * @Description DigestUtils
 * @Author yempty
 * @Date 2020/6/2 10:01
 */
public class DigestUtils {

    public static String HEAD="digest ";

    /**
     * 生成一个随机字符串
     *
     * @return
     */
    public static String generateToken() {
        return IdUtil.simpleUUID();
    }

    public static String md5(String data) {
        return SecureUtil.md5(data);
    }

    /**
     * 该方法用于将 Authorization 请求头的内容封装成一个对象。
     * <p>
     * Authorization 请求头的内容为：
     * Digest username="aaa", realm="no auth", nonce="b2b74be03ff44e1884ba0645bb961b53",
     * uri="/BootDemo/login", response="90aff948e6f2207d69ecedc5d39f6192", qop=auth,
     * nc=00000002, cnonce="eb73c2c68543faaa"
     */
    public static DigestAuthInfo getAuthInfoObject(String authStr) {
        if (authStr == null || authStr.length() <= HEAD.length()) {
            return null;
        }
        if (authStr.toLowerCase().indexOf(HEAD) >= 0) {
            // 截掉前缀 Digest
            authStr = authStr.substring(HEAD.length()-1);
        }

        // 将双引号去掉
        authStr = authStr.replaceAll("\"", "");
        DigestAuthInfo digestAuthObject = new DigestAuthInfo();
        String[] authArray = new String[8];
        authArray = authStr.split(",");

        for (String auth : authArray) {
            String key = auth.substring(0, auth.indexOf("=")).trim();
            String value = auth.substring(auth.indexOf("=") + 1).trim();
            switch (key) {
                case "username":
                    digestAuthObject.setUsername(value);
                    break;
                case "realm":
                    digestAuthObject.setRealm(value);
                    break;
                case "nonce":
                    digestAuthObject.setNonce(value);
                    break;
                case "uri":
                    digestAuthObject.setUri(value);
                    break;
                case "response":
                    digestAuthObject.setResponse(value);
                    break;
                case "qop":
                    digestAuthObject.setQop(value);
                    break;
                case "nc":
                    digestAuthObject.setNc(value);
                    break;
                case "cnonce":
                    digestAuthObject.setCnonce(value);
                    break;
                default:
                    break;
            }
        }
        return digestAuthObject;
    }
}
